package cn.cttic.order.service.impl;

import cn.cttic.app.api.enums.Gender;
import cn.cttic.app.api.enums.InstallOrderStatus;
import cn.cttic.app.api.enums.SaleOrderStatus;
import cn.cttic.common.core.exception.order.OrderException;
import cn.cttic.common.core.utils.BeanCopyUtils;
import cn.cttic.common.core.utils.MapstructUtils;
import cn.cttic.common.core.utils.StringUtils;
import cn.cttic.common.mybatis.core.page.TableDataInfo;
import cn.cttic.common.mybatis.core.page.PageQuery;
import cn.cttic.common.satoken.model.AppLoginUser;
import cn.cttic.common.satoken.utils.AppLoginHelper;
import cn.cttic.link.api.RemoteThirdSmsService;
import cn.cttic.order.api.domain.BaseInstallOrder;
import cn.cttic.order.api.domain.BaseSaleOrder;
import cn.cttic.order.api.domain.bo.BaseSaleOrderBo;
import cn.cttic.order.api.domain.bo.BaseSaleOrderQueryBo;
import cn.cttic.order.api.domain.vo.BaseInstallOrderVo;
import cn.cttic.order.api.domain.vo.BaseSaleOrderVo;
import cn.cttic.order.mapper.BaseInstallOrderMapper;
import cn.cttic.resource.api.RemoteSmsService;
import cn.cttic.resource.api.domain.RemoteSms;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import cn.cttic.order.mapper.BaseSaleOrderMapper;
import cn.cttic.order.service.IBaseSaleOrderService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 销售订单Service业务层处理
 *
 * @author Times.Studio
 * @date 2024-09-17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BaseSaleOrderServiceImpl implements IBaseSaleOrderService {

    private final BaseSaleOrderMapper baseMapper;

    private final BaseInstallOrderMapper baseInstallOrderMapper;

    @DubboReference
    private RemoteThirdSmsService remoteThirdSmsService;

    /**
     * 查询销售订单
     *
     * @param id 主键
     * @return 销售订单
     */
    @Override
    public BaseSaleOrderVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 取消订单
     *
     * @param id 主键
     * @return 销售订单
     */
    @Override
    public BaseSaleOrderVo cancelOrder(String id) {

        log.info("[销售订单][取消订单][开始]");
        log.info("[销售订单][取消订单][入参] {}", id);
        AppLoginUser appLoginUser = AppLoginHelper.getAppLoginUser();

        BaseSaleOrderVo baseSaleOrderVo = baseMapper.selectVoById(id);

        BaseInstallOrderVo baseInstallOrderVo = baseInstallOrderMapper.selectVoOne(
            new LambdaQueryWrapper<BaseInstallOrder>()
                .eq(BaseInstallOrder::getSaleOrderId, id)
        );
        log.info("[销售订单][取消订单][查找安装单] {}", baseInstallOrderVo);

        if (baseInstallOrderVo.getStatus() != InstallOrderStatus.WAITING.getValue()) {
            log.error("[销售订单][取消订单][订单 {} 已经开始安装]", id);
            throw new OrderException("订单" + id + "已经开始安装");
        }

        if (baseInstallOrderMapper.deleteById(baseInstallOrderVo.getId()) > 0) {
            log.info("[销售订单][取消订单][成功]");
            int ret = baseMapper.update(
                new LambdaUpdateWrapper<BaseSaleOrder>()
                    .set(BaseSaleOrder::getInstallOrderId, null)
                    .set(BaseSaleOrder::getStatus, SaleOrderStatus.CANCELED.getValue())
                    .eq(BaseSaleOrder::getId, id));
            if (ret > 0) {
                return baseMapper.selectVoById(id);
            } else {
                throw new OrderException("用户" + appLoginUser.getRealName() + "取消订单" + id + "失败(更新状态)");
            }
        } else {
            log.error("[销售订单][取消订单][用户{}取消订单{}失败]", appLoginUser.getRealName(), id);
            throw new OrderException("用户" + appLoginUser.getRealName() + "取消订单" + id + "失败");
        }
    }

    /**
     * 重新发送通知短信
     *
     * @param id 主键
     * @return 销售订单
     */
    @Override
    public BaseSaleOrderVo resendNoticeMessage(String id) {


        log.info("[销售订单][重新发送通知短信][开始]");
        AppLoginUser appLoginUser = AppLoginHelper.getAppLoginUser();

        BaseSaleOrderVo baseSaleOrderVo = baseMapper.selectVoById(id);

        BaseInstallOrderVo baseInstallOrderVo = baseInstallOrderMapper.selectVoOne(
            new LambdaQueryWrapper<BaseInstallOrder>()
                .eq(BaseInstallOrder::getSaleOrderId, id)
        );
        String callerName = baseSaleOrderVo.getLastName() + Gender.of(baseSaleOrderVo.getGender()).getLabel();

        RemoteSms smsResponse = remoteThirdSmsService.sendInstallCustomerNotice(
            baseSaleOrderVo.getPhone(),
            callerName,
            baseInstallOrderVo.getInstallCode(),
            baseInstallOrderVo.getInstallUrl()
        );
        if (!smsResponse.getSuccess()) {
            log.error("短信发送异常 => {}", smsResponse);
            throw new OrderException("短信发送异常");
        } else {
            log.info("短信发送情况： {}", smsResponse);
            baseInstallOrderVo.setNoticeStatus(1);
            baseInstallOrderVo.setNoticeSmsId(smsResponse.getConfigId());
            baseInstallOrderMapper.updateById(BeanCopyUtils.copy(baseInstallOrderVo, BaseInstallOrder.class));
            return baseSaleOrderVo;
        }
    }

    /**
     * 查询销售订单信息
     *
     * @param id 主键
     * @return 安装订单
     */
    @Override
    public BaseSaleOrderVo getSaleOrderInfoById(String id) {
        return baseMapper.getSaleOrderInfo(id);
    }

    /**
     * 分页查询销售订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 销售订单分页列表
     */
    @Override
    public TableDataInfo<BaseSaleOrderVo> queryPageList(BaseSaleOrderQueryBo bo, PageQuery pageQuery) {
        QueryWrapper<BaseSaleOrder> qw = buildSaleOrderQueryWrapper(bo);
        qw.orderByDesc("saleOrder.create_time");
        Page<BaseSaleOrderVo> result = baseMapper.getSaleOrderPageList(pageQuery.build(), qw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的销售订单列表
     *
     * @param bo 查询条件
     * @return 销售订单列表
     */
    @Override
    public List<BaseSaleOrderVo> queryList(BaseSaleOrderBo bo) {
        return List.of();
    }

    private QueryWrapper<BaseSaleOrder> buildSaleOrderQueryWrapper(BaseSaleOrderQueryBo bo) {
        QueryWrapper<BaseSaleOrder> qw = Wrappers.query();
        qw.eq("saleOrder.del_flag", 0);
        qw.eq(StringUtils.isNotBlank(bo.getChannelType()), "company.channel_type", bo.getChannelType());
        qw.eq(StringUtils.isNotBlank(bo.getProductId()), "product.id", bo.getProductId());
        qw.eq(StringUtils.isNotBlank(bo.getDeviceId()), "device.id", bo.getDeviceId());
        qw.like(StringUtils.isNotBlank(bo.getLastName()), "saleOrder.last_name", bo.getLastName());
        qw.eq(bo.getGender() != null, "saleOrder.gender", bo.getGender());
        qw.like(StringUtils.isNotBlank(bo.getPhone()), "saleOrder.phone", bo.getPhone());
        qw.like(StringUtils.isNotBlank(bo.getCarNo()), "saleOrder.car_no", bo.getCarNo());
        qw.eq(StringUtils.isNotBlank(bo.getSalesManId()), "saleOrder.sales_man_id", bo.getSalesManId());
        qw.like(StringUtils.isNotBlank(bo.getSaleOrderId()), "saleOrder.id", bo.getSaleOrderId());
        qw.like(StringUtils.isNotBlank(bo.getInstallOrderId()), "saleOrder.install_order_id", bo.getInstallOrderId());
        qw.eq(bo.getStatus() != null, "saleOrder.status", bo.getStatus());
        return qw;
    }

    /**
     * 新增销售订单
     *
     * @param bo 销售订单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BaseSaleOrderBo bo) {
        BaseSaleOrder add = MapstructUtils.convert(bo, BaseSaleOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改销售订单
     *
     * @param bo 销售订单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BaseSaleOrderBo bo) {
        BaseSaleOrder update = MapstructUtils.convert(bo, BaseSaleOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseSaleOrder entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除销售订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
